﻿using System;
using System.Threading;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Diagnostics;

namespace a17_TaskAsyncPattern
{
    class Program
    {
        /*
          运行的结果输出一种,
           
          call Sync, tid=9
          Add(), tid=9
          Sync result=3
          call Async, tid=9
          AddAsync 1, tid=9
          AddAsync 2, tid=9           
          Add(), tid=10               注意此处运行在worker thread.
          task wait, tid=9
          AddAsync 3, tid=10          注意此处运行在worker thread.
          Async result=7, tid=9
       */
        static void Main(string[] args)
        {
            int sum = 0;
            Debug.WriteLine("call Sync, tid=" + Thread.CurrentThread.ManagedThreadId);
            sum = AddSync(1, 2);
            Debug.WriteLine("Sync result=" + sum);


            Debug.WriteLine("call Async, tid=" + Thread.CurrentThread.ManagedThreadId);
            Task<int> t = AddAsync(3, 4);
            Debug.WriteLine("task wait, tid=" + Thread.CurrentThread.ManagedThreadId);
            t.Wait();

            Debug.WriteLine("Async result=" + t.Result + ", tid=" + Thread.CurrentThread.ManagedThreadId);
        }

        private static int Add(int a, int b)
        {
            Debug.WriteLine("Add(), tid=" + Thread.CurrentThread.ManagedThreadId);
            return a + b;
        }
        private static int AddSync(int a, int b)
        {
            return Add(a, b);
        }
        
        private static async Task<int> AddAsync(int a, int b)
        {
            Debug.WriteLine("AddAsync 1, tid=" + Thread.CurrentThread.ManagedThreadId);
            Func<int> dg = new Func<int>(() => Add(a, b));
            Debug.WriteLine("AddAsync 2, tid=" + Thread.CurrentThread.ManagedThreadId);
            int sum = await Task<int>.Run(dg);
            Debug.WriteLine("AddAsync 3, tid=" + Thread.CurrentThread.ManagedThreadId);
            return sum;
        }

    }
}
